const express = require('express');
const { query } = require('../config/database-sqlite');
const { optionalAuth, authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取歌单列表
router.get('/', optionalAuth, async (req, res) => {
  try {
    const { page = 1, limit = 20, user_id, keyword } = req.query;
    const offset = (page - 1) * limit;

    let sql = `
      SELECT p.*, u.nickname as creator_name,
             (SELECT COUNT(*) FROM playlist_songs ps WHERE ps.playlist_id = p.id) as song_count
      FROM playlists p
      LEFT JOIN users u ON p.user_id = u.id
      WHERE p.status = 1 AND p.is_public = 1
    `;
    const params = [];

    if (user_id) {
      sql += ' AND p.user_id = ?';
      params.push(user_id);
    }

    if (keyword) {
      sql += ' AND p.name LIKE ?';
      params.push(`%${keyword}%`);
    }

    sql += ' ORDER BY p.like_count DESC, p.created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));

    const playlists = await query(sql, params);

    res.json({
      playlists,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        hasMore: playlists.length === parseInt(limit)
      }
    });

  } catch (error) {
    console.error('获取歌单列表错误:', error);
    res.status(500).json({ error: '获取歌单列表失败' });
  }
});

// 获取歌单详情
router.get('/:id', optionalAuth, async (req, res) => {
  try {
    const { id } = req.params;

    const playlists = await query(`
      SELECT p.*, u.nickname as creator_name
      FROM playlists p
      LEFT JOIN users u ON p.user_id = u.id
      WHERE p.id = ? AND p.status = 1
    `, [id]);

    if (playlists.length === 0) {
      return res.status(404).json({ error: '歌单不存在' });
    }

    const playlist = playlists[0];

    // 检查访问权限
    if (!playlist.is_public && (!req.user || req.user.id !== playlist.user_id)) {
      return res.status(403).json({ error: '无权访问此歌单' });
    }

    // 获取歌单中的歌曲
    const songs = await query(`
      SELECT s.*, a.name as artist_name, ps.sort_order, ps.added_at
      FROM playlist_songs ps
      JOIN songs s ON ps.song_id = s.id
      LEFT JOIN artists a ON s.artist_id = a.id
      WHERE ps.playlist_id = ? AND s.status = 1
      ORDER BY ps.sort_order ASC, ps.added_at DESC
    `, [id]);

    playlist.songs = songs;
    playlist.song_count = songs.length;

    res.json({ playlist });

  } catch (error) {
    console.error('获取歌单详情错误:', error);
    res.status(500).json({ error: '获取歌单详情失败' });
  }
});

// 创建歌单
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { name, description, cover_url, is_public = 1, tags } = req.body;

    if (!name || name.trim().length === 0) {
      return res.status(400).json({ error: '歌单名称不能为空' });
    }

    const result = await query(`
      INSERT INTO playlists (name, description, cover_url, user_id, is_public, tags)
      VALUES (?, ?, ?, ?, ?, ?)
    `, [name.trim(), description || '', cover_url || '', req.user.id, is_public, tags || '']);

    res.status(201).json({
      message: '歌单创建成功',
      playlist_id: result.insertId
    });

  } catch (error) {
    console.error('创建歌单错误:', error);
    res.status(500).json({ error: '创建歌单失败' });
  }
});

// 更新歌单信息
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description, cover_url, is_public, tags } = req.body;

    // 检查歌单是否存在且属于当前用户
    const playlists = await query(
      'SELECT id FROM playlists WHERE id = ? AND user_id = ? AND status = 1',
      [id, req.user.id]
    );

    if (playlists.length === 0) {
      return res.status(404).json({ error: '歌单不存在或无权限修改' });
    }

    const updateData = {};
    const params = [];

    if (name !== undefined) {
      updateData.name = '?';
      params.push(name.trim());
    }
    if (description !== undefined) {
      updateData.description = '?';
      params.push(description);
    }
    if (cover_url !== undefined) {
      updateData.cover_url = '?';
      params.push(cover_url);
    }
    if (is_public !== undefined) {
      updateData.is_public = '?';
      params.push(is_public);
    }
    if (tags !== undefined) {
      updateData.tags = '?';
      params.push(tags);
    }

    if (Object.keys(updateData).length === 0) {
      return res.status(400).json({ error: '没有要更新的数据' });
    }

    const sql = `UPDATE playlists SET ${Object.keys(updateData).map(key => `${key} = ?`).join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
    params.push(id);

    await query(sql, params);

    res.json({ message: '歌单更新成功' });

  } catch (error) {
    console.error('更新歌单错误:', error);
    res.status(500).json({ error: '更新歌单失败' });
  }
});

// 删除歌单
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    // 检查歌单是否存在且属于当前用户
    const playlists = await query(
      'SELECT id FROM playlists WHERE id = ? AND user_id = ? AND status = 1',
      [id, req.user.id]
    );

    if (playlists.length === 0) {
      return res.status(404).json({ error: '歌单不存在或无权限删除' });
    }

    // 软删除歌单
    await query('UPDATE playlists SET status = 0 WHERE id = ?', [id]);

    res.json({ message: '歌单删除成功' });

  } catch (error) {
    console.error('删除歌单错误:', error);
    res.status(500).json({ error: '删除歌单失败' });
  }
});

// 添加歌曲到歌单
router.post('/:id/songs/:songId', authenticateToken, async (req, res) => {
  try {
    const { id, songId } = req.params;

    // 检查歌单是否存在且属于当前用户
    const playlists = await query(
      'SELECT id FROM playlists WHERE id = ? AND user_id = ? AND status = 1',
      [id, req.user.id]
    );

    if (playlists.length === 0) {
      return res.status(404).json({ error: '歌单不存在或无权限操作' });
    }

    // 检查歌曲是否存在
    const songs = await query('SELECT id FROM songs WHERE id = ? AND status = 1', [songId]);
    if (songs.length === 0) {
      return res.status(404).json({ error: '歌曲不存在' });
    }

    // 检查歌曲是否已在歌单中
    const existing = await query(
      'SELECT id FROM playlist_songs WHERE playlist_id = ? AND song_id = ?',
      [id, songId]
    );

    if (existing.length > 0) {
      return res.status(400).json({ error: '歌曲已在歌单中' });
    }

    // 获取当前最大排序号
    const [maxSort] = await query(
      'SELECT COALESCE(MAX(sort_order), 0) as max_sort FROM playlist_songs WHERE playlist_id = ?',
      [id]
    );

    // 添加歌曲到歌单
    await query(
      'INSERT INTO playlist_songs (playlist_id, song_id, sort_order) VALUES (?, ?, ?)',
      [id, songId, maxSort.max_sort + 1]
    );

    // 更新歌单歌曲数量
    await query(
      'UPDATE playlists SET song_count = (SELECT COUNT(*) FROM playlist_songs WHERE playlist_id = ?) WHERE id = ?',
      [id, id]
    );

    res.json({ message: '歌曲添加成功' });

  } catch (error) {
    console.error('添加歌曲错误:', error);
    res.status(500).json({ error: '添加歌曲失败' });
  }
});

// 从歌单中移除歌曲
router.delete('/:id/songs/:songId', authenticateToken, async (req, res) => {
  try {
    const { id, songId } = req.params;

    // 检查歌单是否存在且属于当前用户
    const playlists = await query(
      'SELECT id FROM playlists WHERE id = ? AND user_id = ? AND status = 1',
      [id, req.user.id]
    );

    if (playlists.length === 0) {
      return res.status(404).json({ error: '歌单不存在或无权限操作' });
    }

    const result = await query(
      'DELETE FROM playlist_songs WHERE playlist_id = ? AND song_id = ?',
      [id, songId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '歌曲不在歌单中' });
    }

    // 更新歌单歌曲数量
    await query(
      'UPDATE playlists SET song_count = (SELECT COUNT(*) FROM playlist_songs WHERE playlist_id = ?) WHERE id = ?',
      [id, id]
    );

    res.json({ message: '歌曲移除成功' });

  } catch (error) {
    console.error('移除歌曲错误:', error);
    res.status(500).json({ error: '移除歌曲失败' });
  }
});

module.exports = router;